import React, { PropTypes, Component } from 'react';
import { Link } from 'react-router';
import style from './WorkloadM.css';
import tips from './../imgs/workload_tips.png'
import {myAjaxGet, getAdminInfo, getAuthShop, isLogining, myAjaxJson, ROOTURL } from './../publicAPI/publicAPI';




export default React.createClass({
	getInitialState: function() {
		let _this = this;
		
		//获取当前登录信息，用于记录订单修改人
		getAdminInfo(function(data) {
			console.log(data);
			this.setState({
				userId: data.id,
				userName: data.uname,
			});
		}.bind(_this), function(error) {})

      	//获取所有店铺名与id对应信息
		getAuthShop(null, function(data) {
			console.log(data);
			var shopsForAdm = [];
			let shopsId = {};//[id]-name
			let shopsM = {};
			data.forEach((shopMes) => {
				shopsForAdm.push(shopMes.dname);
				shopsId[shopMes.id] = shopMes.dname;
				shopsM[shopMes.dname] = shopMes.id;
			}); 
			console.log(shopsForAdm);
			this.setState({
				shopsData: data,
				shopsForAdm: shopsForAdm,
				shopsId: shopsId,
				shopsM: shopsM,
			}, this.getServantM());
		}.bind(_this));

		

	    return {
	    	shopsForAdm: [],
	    	baberArray: [],
	    	//shopsData: [],
	    	assistantArray: [],
	    	serTypesForShop: [],
	    	showTips: false,

	    	
	    	//订单状态
	        shop: '',
	        baber: '',
	        serType: '',
	        grossPay: '',
	        netPay: '',
	        payment: '',
	        assistant: '',
	        isChoosed: false,
	        tmServe: 0,
	        message: '',
	        //tmCreate: 0,
	        creator: '',
	        //tmChange: 0,
	        changer: '',
	        //是否有从订单
	        attachingId: '',
		};
	},

	componentWillMount: function() {
		//let _this = this;

	},
	componentDidMount: function() {
		//let _this = this;
	
	},

	getServantM: function() {
		let _this = this;
		//获取所有服务人员信息
        myAjaxJson(ROOTURL +'servant/profile/search.api', 'POST', {}, function(data) {
        	console.log(data);
        	let servantsM = {};//[id]-name
        	let servantsId = {};//[name]-id
        	data.forEach(function(servant) {
          		servantsM[servant.id] = servant.meta.name;
          		servantsId[servant.meta.name] = servant.id;
        	});
        	console.log(servantsM);
        	this.setState({
        		servantsData: data,
            	servantsM: servantsM,
            	servantsId: servantsId,
        	},_this.handleGetInfo());
        	
      	}.bind(_this), function(error) {})
	},

	handleGetInfo: function() {
		let _this = this;
		//获取要修改的订单信息
		myAjaxGet(ROOTURL +'contract/offline/instance.api', {id: this.props.params.id}, function(data) {
			console.log(data);
			console.log(this.state.servantsM[data.servantId]);
			this.setState({
				shop: this.state.shopsId[data.shopId],
		        baber: this.state.servantsM[data.servantId],
		        serType: data.meta.serType,
		        grossPay: data.grossPay,
		        netPay: data.netPay,
		        payment: data.meta.payment,
		        assistant: data.meta.assistant,
		        isChoosed: data.meta.isChoosed,
		        tmServe: data.tmServe,
		        message: data.meta.message,
		        tmCreate: data.tmCreate,
		        creator: data.meta.creatorName,
		        tmChange: data.meta.tmChange||null,
		        whoChange: data.meta.whoChange||'无',
		        isChecked: data.meta.isChecked,
		        permission: data.meta.permission,
		        whoChecked: data.meta.whoChecked,
			}, this.searchAttaching(this.props.params.id));
		}.bind(_this), function(error) {});
	},

	//查询该订单是否有从订单
	searchAttaching: function(id) {
		let _this = this;
		myAjaxJson(ROOTURL +'contract/offline/search.api', 'POST', {attaching: this.props.params.id}, function(data) {
			console.log(data);
			data.map(function(searchData, idx) {
				if(searchData.attaching&&!searchData.dd) {
					//let attachingIds = [];
					_this.setState({
						attachingId: searchData.id,
					});
				}
			});
		}, function(error) {});
	},

	//这几个render函数可以写成无状态函数，即把要用的state当做变量传入，而不是直接调用
	//过多的使用state会让数据流混乱
	renderBaber: function(shopSelect) {

		let baberArray = this.state.servantsData.filter(function(servantData) {
		    return !servantData.dd&&(servantData.meta.shop==shopSelect)&&(!servantData.meta.isAssistant)
		});
		//console.log(baberArray);
		return (
			baberArray.map((baberData, idx) => {
				return <option value={baberData.meta.name} key={idx} >{baberData.meta.name}</option>
			})
		);
	},

	renderAssistant: function(shopSelect) {
		let assistantArray = this.state.servantsData.filter(function(servantData) {
		    return !servantData.dd&&(servantData.meta.shop==shopSelect)&&servantData.meta.isAssistant
		});
		return (
			assistantArray.map((assistantData, idx) => {
				return <option value={assistantData.meta.name} key={idx} >{assistantData.meta.name}</option>
			})
		);
	},

	renderSerType1: function(shopSelect) {
		console.log(shopSelect);
		let _this = this;
		let shopSelectData = this.state.shopsData.filter((shop, idx) => {
        	if(shop.dname == shopSelect) {
        		return true
        	} else { return false }
        });

        myAjaxJson(ROOTURL + '/serv/shop/search.api', 'POST', {id: shopSelectData.id, name: shopSelectData.dname}, function(data) {
			console.log(data);
            let serTypesId = {};//[name]-id
            let serTypesForShop = data.filter((type, idx)=> {
                serTypesId[type.dname] = type.id;
                return !type.dd
            });
            console.log(serTypesForShop);
            this.setState({
                serTypesForShop: serTypesForShop,
                serTypesId: serTypesId,
            });
        }.bind(_this), function(error) {});

	},

	renderSerType2: function(serTypesForShop) {
		return (
			serTypesForShop.map((servType, idx) => {
				return <option value={servType.dname} key={idx} >{servType.dname}</option>
			})
		);
	},

	renderPermission: function(permission) {
		if(permission) {
			return (
				<div className={style['workloadM_permission_green']}>
					<span className={style['workloadM_permissionM']}>审核通过</span>
				</div>
			);
		} else {
			return (
				<div className={style['workloadM_permission_red']}>
					<span className={style['workloadM_permissionM']}>不予通过</span>
				</div>
			);
		}	
	},

	handleSubmit: function() {
		let _this = this;
		let nowTime = new Date();
		//let crTime = this.state.tmServe||nowTime.setHours(this.refs.crHour.value, this.refs.crMinute.value);
		//console.log(crTime);

		//判断订单是否已复核过
		if(this.state.isChecked) {
			return
		}

		//判断数据是否为空，是否格式正确
		if(!parseFloat(this.refs.netPay.value)) {
			alert('价格错误，请检查格式是否正确！');
			return 
		}

		//发送数据至服务器
		let param = {};
		//param.creator = this.state.userid;
		//订单创建时间
        //param.tmCreate = this.state.tmCreate||nowTime.getTime();
        param.id = this.props.params.id;
		param.dd = false;
		//param.customer = this.refs.customer.value;
		param.servant = this.state.servantsId[this.refs.baberName.value];
        param.shop = this.state.shopsM[this.refs.shopSelect.value];
        param.servType= this.state.serTypesId[this.refs.serType.value];
        //标准价格
        //param.grossPay = parseFloat(this.refs.grossPay.value);
        //实际支付价格
        param.netPay = parseFloat(this.refs.netPay.value);
        //服务开始时间
        //param.tmServe = this.state.tmServe;
        param.meta =  {
            //是否是顾客指定理发师
            isChoosed: this.refs.isChoosed.checked,
            //支付方式
            payment: this.refs.payment.value,
            //备注
            message: this.refs.message.value,
            //订单创建人
            creatorName: this.state.userName,
            //服务类型
            serType: this.refs.serType.value,
            //理发师助理
            assistant: this.refs.assistant.value||'无',
            //记录订单最后修改
            whoChange: this.state.userName,
            //记录订单最后修改时间
            tmChange: nowTime.getTime(),
        }
        //没写的项目
        //param.stPayment = 16;//支付状态
        //param.tmReserve = crTime;//预计接受服务时刻
        console.log(param);

		myAjaxJson(ROOTURL + 'contract/offline/instance.api', 'POST', param, function(data3) {
			console.log(data3);
			console.log(_this.state.attachingId);
			if(_this.state.attachingId&&_this.state.changeAssistant) {
				//有从订单并且修改
				if(_this.refs.assistant.value != '无') {
					//从当前助理修改为另一个助理
					param.id = _this.state.attachingId;
					param.servant = _this.state.servantsId[_this.refs.assistant.value];
					console.log(param);
					myAjaxJson(ROOTURL + 'contract/offline/instance.api', 'POST', param, function(data) {
						console.log(data);
						console.log('修改从订单成功');

						alert('修改成功');
						window.location.href = `/SalaryM/WorkloadM/${_this.props.params.id}`;
					}, function(error) {alert('修改失败，修改从订单失败')});
				} else {
					//将助理修改为无，执行删除操作
					let token = isLogining();
					fetch(ROOTURL + 'contract/offline/instance.api?id=' + _this.state.attachingId, {
		                method: 'DELETE',
		                headers: {
		                  	"X-Cafune-Authentication": "SECRET",
		                  	"X-Cafune-Session-Token": token,
		                  	"Content-type": "application/json; charset=UTF-8"
		                },
		                body: JSON.stringify({})
		            })
		            .then((res) => {
		                if(res.ok) {
		                	console.log(_this.state.attachingId);
		                  	console.log('删除从订单成功');

		                  	alert('修改成功');
							window.location.href = `/SalaryM/WorkloadM/${_this.props.params.id}`;
		                }
		            })
		            .catch((err) => {
		                alert('删除失败,从订单删除失败');
		            });
				}
				
			} else if (!_this.state.attachingId&&_this.state.changeAssistant) {
				//没有从订单(助理)但修改后有,执行创建从订单操作
				if(_this.refs.assistant.value == '无') {
					alert('修改成功');
					window.location.href = `/SalaryM/WorkloadM/${_this.props.params.id}`;
				} else {
					param.id = null;
					param.attaching = _this.props.params.id;
					param.servant = _this.state.servantsId[_this.refs.assistant.value];
					console.log(param);
					//创建理发师助理订单
					myAjaxJson(ROOTURL + 'contract/offline/instance.api', 'POST', param, function(data) {
						console.log(data);
						console.log('创建从订单(助理)成功');
						alert('修改成功');
						window.location.href = `/SalaryM/WorkloadM/${_this.props.params.id}`;
					}, function(error) {
						alert('修改理发师助理失败,创建从订单失败');
					});
				}
			}

			//alert('录入成功');
			//window.location.href = `/SalaryM/WorkloadM/${_this.props.params.id}`;
		}, function(error3) {
			alert('录入失败');
		});
		
	},

	handleKeyPress: function(e) {
	    if(e.which == 13) {
	        this.handleSubmit();
	    }
	},

	//接下来是冗余的数据双向绑定，如果react有其他办法实现请告诉我！谢谢！
	changeShop: function(e) {
		console.log(e.target.value);
		let _this = this;
	    this.setState({
			shop: e.target.value,
			serTypesForShop: [],
			showTips: true,
		});
	},
	changeBarber: function(e) {
		//console.log(e.target.value);
		this.setState({
			baber: e.target.value,
		});
	},
	changeSerType: function(e) {
		this.setState({
			serType: e.target.value,
		});
	},
	changeNetPay: function(e) {
		this.setState({
			netPay: e.target.value,
		});
	},
	changeAssistant: function(e) {
		this.setState({
			assistant: e.target.value,
			changeAssistant: true,
		});
	},
	changePayment: function(e) {
		this.setState({
			payment: e.target.value,
		});
	},
	changeIsChoosed: function() {
		this.setState({
			isChoosed: !this.state.isChoosed,
		});
	},
	changeMes: function(e) {
		this.setState({
			message: e.target.value,
		});
	},

	render: function() {
		let tmCreate = new Date(this.state.tmCreate);
		let tmChange = new Date(this.state.tmChange);
		let tmServe = new Date(this.state.tmServe);
		//console.log(this.state);
		//console.log(this.state.shop);
		//console.log(this.state.serType);
		console.log(this.state.isChecked);
		return (
			<div className={style['workloadM_wrapper']}>
				<div className={style['workloadM_header']}>
					<div className={style['workloadM_create']}>
						<p>订单号：<span>{this.props.params.id}</span></p>
						<p>审核人：<span>{this.state.whoChecked}</span></p>
					</div>
					<div className={style['workloadM_create']}>
						<p>订单创建时间：
							{
								this.state.tmCreate?
							    (
									<span>
										{tmCreate.getFullYear()}年
										{tmCreate.getMonth()}月
										{tmCreate.getDate()}日-
										{tmCreate.getHours()}:
										{tmCreate.getMinutes()}
									</span>
								) : (<span>无</span>)
							}
						</p>
						<p>订单创建人：{this.state.creator}</p>
					</div>
					<div className={style['workloadM_change']}>
						<p>订单最后一次修改时间：
							{
								this.state.tmChange?
							    (
									<span>
										{tmChange.getFullYear()}年
										{tmChange.getMonth()}月
										{tmChange.getDate()}日-
										{tmChange.getHours()}:
										{tmChange.getMinutes()}
									</span>
								) : (<span>无</span>)
							}
						</p>
					<p>订单最后一次修改人：{this.state.whoChange}</p>
					</div>
					{
							this.state.isChecked? this.renderPermission(this.state.permission) : null
					}
				</div>

		    	<div>
					<form className={style['workloadM_form']}>
						<p>
						<label>店铺名称：</label>
				    	<select value={this.state.shop} ref="shopSelect" onChange={this.changeShop}>
				    		<option value={this.state.shop}>{this.state.shop}</option>
				    		<option disabled="true">--------------请从下面选择---------------</option>	    		
				    		{
			                    this.state.shopsForAdm.map((shop, idx) => {
			                    	return (
		                                <option value={shop} key={idx+1}>{shop}</option>
			                    	);
			                    })
				    		}
				    	</select>
				    	</p>

				    	<p>
				    	<label>理发师姓名：</label>
				    	<select value={this.state.baber} ref="baberName" onChange={this.changeBarber} >
				    		<option value={this.state.baber}>{this.state.baber}</option>
				    		<option disabled="true">--------------请从下面选择---------------</option>
							{
								this.state.shop? this.renderBaber(this.state.shop) : null
							}
			    		</select>
			    		</p>

						<p>
							<label>服务项目：</label>
							<select value={this.state.serType} ref="serType" onChange={this.changeSerType} >
								<option value={this.state.serType}>{this.state.serType}</option>
								<option disabled="true">--------------请从下面选择---------------</option>
								{
									this.state.shop&&!this.state.serTypesForShop[0]? this.renderSerType1(this.state.shop) : null
								}
								{
									this.state.serTypesForShop[0]? this.renderSerType2(this.state.serTypesForShop) : null
								}
							</select>
						</p>

						<p>
								<label>标准价格：</label><span>{this.state.grossPay}</span>&nbsp;&nbsp;&nbsp;
								<label>实收价格：</label><input type="text" value={this.state.netPay} ref="netPay" onChange={this.changeNetPay} />
						</p>
						
						<p>
							<label>收款渠道：</label>
							<select value={this.state.payment} ref="payment" onChange={this.changePayment} >
								<option value="拉卡拉">拉卡拉</option>
								<option value="大众点评">大众点评</option>
								<option value="百度糯米">百度糯米</option>
								<option value="充值机">充值机</option>
							</select>
						</p>

						<p>
							<label>助理：</label>
							<select value={this.state.assistant} ref="assistant" onChange={this.changeAssistant} >
								<option value={this.state.assistant}>{this.state.assistant}</option>
								<option disabled="true">--------------请从下面选择---------------</option>
								<option value={'无'}>无</option>
								{
									this.state.shop? this.renderAssistant(this.state.shop) : null
								}
							</select>
						</p>

						<p>
							<label style={{width: '200px'}}>顾客是否指定该理发师：</label>
							<input checked={this.state.isChoosed} type="checkbox" ref="isChoosed" onChange={this.changeIsChoosed} />
						</p>

						<p><label style={{width: '115px'}}>服务开始时间：</label>{tmServe.getFullYear()}年{tmServe.getMonth()+1}月{tmServe.getDate()}日{tmServe.getHours()}:{tmServe.getMinutes()}</p>
						<p><label>备注：</label><input type="text" ref="message" value={this.state.message} onChange={this.changeMes} /></p>
					</form>
		    	</div>
		    	{
		    		this.state.showTips? 
		    			(<div className={style['workloadM_tips']}>
							<p><img src={tips} />&nbsp;&nbsp;修改门店后，请重新选择<b>理发师</b>、<b>服务类型</b>、<b>助理</b>等选项并确认</p>
		    			</div>) : null
		    	}
		    	<div>
					<button className={style['workloadM_button']} style={this.state.isChecked? {display: 'none'} : {display: 'block'}} onClick={this.handleSubmit}>修改</button>
					<Link to={`/SalaryM/WorkloadTable`}>
						<button className={style['workloadM_button']}>返回</button>
					</Link>
				</div>
    		</div>
		);
		
	}
});
    
